// 调用 vite API 进行构建打包
import * as fs from 'fs'
import { resolve } from 'path'
import { build, defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import outputRaw from './build/plugins/outputRaw'
import defaultOptions from './build/defaultOptions'

fs.rmSync(resolve('dist'), { force: true, recursive: true })

const isBuildExt = process.argv.includes('--build-ext')

const common = {
  resolve: {
    alias: {
      '~': resolve('./src'),
    }
  },
  define: {
    __EXT__: !process.argv.includes('--web'),
    __CONFIG__: defaultOptions
  }
}

async function bootstrap() {
  const libs = [
    {
      name: 'background',
      input: 'src/background/index.ts'
    },
    {
      name: 'page',
      input: 'src/injects/index.ts'
    }
  ]

  for (const item of libs) {
    await build({
      ...common,
      configFile: false,
      plugins: [vue()],
      build: {
        rollupOptions: {
          input: resolve(__dirname, item.input),
          output: {
            format: 'iife',
            inlineDynamicImports: true,
            dir: resolve(__dirname, 'dist'),
            entryFileNames: `${item.name}.js`
          }
        },
        minify: isBuildExt,
        watch: isBuildExt ? null : {},
        emptyOutDir: false
      }
    })
  }
}

bootstrap()

export default defineConfig({
  ...common,
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "~/styles/index.scss" as *;`,
      },
    },
  },
  build: {
    emptyOutDir: false
  },
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      dirs: [],
      resolvers: [ElementPlusResolver({
        importStyle: "sass",
      })],
    }),
    outputRaw([
      { source: resolve(__dirname, 'src/manifest.json') }
    ])
  ]
})